﻿using MuXue.Zyiz.Template.Domain.Entity;
using MuXue.Zyiz.Template.Domain.IRepository;
using MuXue.Zyiz.Template.Domain.Model;
using MuXue.Zyiz.Template.Infrastructure;
using MuXue.Zyiz.Template.Infrastructure.Repository;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using AutoMapper;
using MuXue.Zyiz.Template.Common.Redis;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MuXue.Zyiz.Template.Common;
using System.Threading.Tasks;
using MuXue.Zyiz.Template.Domain.Model.response;
using MuXue.Zyiz.Template.Domain.Model.Request;
using System.Linq.Expressions;
using Microsoft.Extensions.Configuration;
using System.Net.Http;
using MuXue.Zyiz.Template.OuterClient;

namespace MuXue.Zyiz.Template.Service.Impl
{

    /// <summary>
    /// 【Demo类，可以删除】订单处理
    /// </summary>
    public class ordersService : IordersService
    {
        private IDbContext _dbContext;
        private IUnitOfWork _unitOfWork;
        private IordersRepository _ordersRepository;
        private IordercourseRepository _ordercourseRepository;
        private IMapper _mapper; 
        private ILogger _logger;
        private readonly IConfiguration _config;
        private readonly IHttpClientFactory _clientFactory;

        public ordersService(IDbContext dbContext, IMapper mapper, ILogger<ordersService> logger, IConfiguration config, IHttpClientFactory clientFactory)
        {
            _dbContext = dbContext;
            _unitOfWork = new UnitOfWork(_dbContext);
            _ordersRepository = new ordersRepository(_dbContext);
            _ordercourseRepository = new ordercourseRepository(_dbContext);
            _mapper = mapper;
            _config = config;
            _logger = logger;
            _clientFactory = clientFactory;
        }

        /// <summary>
        ///  【列表Demo】获取订单列表
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public async Task<Result<List<SmallOrderResp>>> GetList(string app_user_id)
        {
            Result<List<SmallOrderResp>> result = new Result<List<SmallOrderResp>>();
            try
            {

                List<SmallOrderResp> orderlist = await _ordersRepository.QueryListSmallModel(app_user_id);
                if (orderlist != null && orderlist.Count() > 0)
                {
                    result.state = true;
                    result.data = orderlist;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询订单列表错误：" + ex.Message);
            }

            return result;
        }

        /// <summary>
        ///【详情Demo】 订单详情
        /// </summary>
        /// <param name="app_user_id"></param>
        /// <param name="order_no"></param>
        /// <returns></returns>
        public async Task<Result<OrderDetailResp>> QueryDetailByOrderNo(string app_user_id, string order_no)
        {
            Result<OrderDetailResp> result = new Result<OrderDetailResp>();

            try
            {
                OrderDetailResp odetailResp = new OrderDetailResp(); 
                cs_orders order = _ordersRepository.WhereLoadEntity(p => p.order_no == order_no && p.app_user_id == app_user_id);

                if (order != null && order.id > 0)
                {
                    odetailResp = _mapper.Map<OrderDetailResp>(order);
                    cs_order_course o_course = _ordercourseRepository.WhereLoadEntity(p => p.order_no == order_no);
                    if (o_course != null && o_course.id > 0)
                    {
                        OrderCourseResp ocResp = _mapper.Map<OrderCourseResp>(o_course);
                        odetailResp.course = ocResp;
                    }
                    result.state = true;
                    result.data = odetailResp;
                }
                else
                {
                    result.state = false;
                    result.error_msg = "该用户的订单号不存在";
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询订单详情错误：" + ex.Message);
            }
            return result;
        }


         
 
        /// <summary>
        /// 【部分修改Demo】用户主动取消退费
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Result<string>> CancelOrder(OrderDetailReq req)
        {
            Result<string> result = new Result<string>();

            try
            {
                cs_orders lookOrder = _ordersRepository.WhereLoadEntity(p => p.order_no == req.order_no.Trim() && p.app_user_id == req.app_user_id);
                if (lookOrder == null || lookOrder.id <= 0)
                {
                    result.state = false;
                    result.error_code = ErrorCode.SqlExcuteError;
                    result.error_msg = "未查询到该订单";
                    return result;
                }
                if (lookOrder.order_status != 0)
                {
                    result.state = false;
                    result.error_code = ErrorCode.ParamError;
                    result.error_msg = "该订单无法取消";
                    return result;
                }


                DateTime now = DateTime.Now;
                lookOrder.order_status = 2;
                lookOrder.canel_time = now;
                lookOrder.canel_case = "主动取消";
                lookOrder.update_time = now;
                lookOrder.update_remark += "-主动取消";

                Expression<Func<cs_orders, object>>[] updatedProperties = {
                            p => p.order_status,
                             p => p.canel_time,
                              p => p.canel_case,
                               p => p.update_time,
                             p => p.update_remark
                        };

                int sqlOk = _ordersRepository.UpdateEntity(lookOrder, updatedProperties);

                if (sqlOk > 0)
                {
                    result.state = true;
                }
                else
                {
                    result.state = false;
                    result.error_code = ErrorCode.SqlExcuteError;
                    result.error_msg = "主动取消失败！";
                }
            }
            catch (Exception ex)
            {
                result.state = false;
                result.error_msg = ex.Message;
                result.error_code = ErrorCode.SysExceptionError;
                _logger.LogError(ex, "主动取消报错：" + ex.Message);
                return result;
            }



            return result;
        }


        /// <summary>
        /// 【调用第三方接口Demo】
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public async Task<Result<string>> ZyizCheckDept(CheckSchoolDeptReq req)
        {
            Result<string> sendRet = new Result<string>();

            try
            {
                HttpClient client = _clientFactory.CreateClient("ContractApi");
              
                MarketToZyizCheckReq checkreq = new MarketToZyizCheckReq();
                checkreq.belong = "选课排班商城系统";
                checkreq.deptcode = req.school_code;
                checkreq.marketId = req.app_user_id;
                checkreq.odate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
                checkreq.type = "1";
                checkreq.studentid = req.zyiz_user_id;
                sendRet = await ZyizHttpClientExtensions.PostData<Result<string>>(client, _logger,"OMOMarket/MarketToZyizCheck", checkreq);
            }
            catch (Exception ex)
            {
                sendRet.state = false;
                sendRet.error_code = ErrorCode.SysExceptionError;
                sendRet.error_msg = "调用《电商订单检查是否可以下订单接口》报错了。请重试或者联系管理员！";
                _logger.LogError(ex, "调用《电商订单检查是否可以下订单》接口报错了：" + ex.Message);
            }

            return sendRet;
        }

    }
}
